package com.atguigu.yyhg.msm.controller;


import com.atguigu.yygh.common.result.Result;
import com.atguigu.yyhg.msm.service.MsmService;
import com.atguigu.yyhg.msm.utils.RandomUtil;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @Auther: chao
 * @Date:2021/7/11-07-11-17:30
 * @Description:com.atguigu.yyhg.msm.controller
 * @version:1.0
 */
@RestController
@RequestMapping("/api/msm")
public class MsmApiController {
    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发送手机验证码
    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone){
        //从redis获取验证码，获取到返回ok key是手机号 value是验证码
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return Result.ok();
        }

        //获取不到，生成验证码，通过短信服务整合发送
        code = RandomUtil.getSixBitRandom();
        boolean isSend = msmService.send(phone,code);
        //生成验证码放到redis
        if (isSend){
            redisTemplate.opsForValue().set(phone,code,2, TimeUnit.MINUTES);
            return Result.ok();
        }else {
            return Result.fail().message("发送短信失败");
        }

    }
}
